package com.dpkit.configuration;

import com.dpkit.adapter.OrmAdapter;
import com.dpkit.core.DPKitCoreEngine;
import com.dpkit.core.DPKitDPKitCoreEngineImpl;
import com.dpkit.manager.factory.DynamicEntityFactory;
import com.dpkit.processor.DPKitTemplateProcessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ResourceLoader;

/**
 * DPKit核心自动配置类
 * 配置基础Bean和通用功能
 */
@Configuration
@ConditionalOnClass(DPKitTemplateProcessor.class)
@EnableConfigurationProperties(DPKitProperties.class)
@AutoConfigureAfter({DataSourceAutoConfiguration.class})
public class DPKitAutoConfiguration {
    
    private final DPKitProperties properties;
    
    public DPKitAutoConfiguration(DPKitProperties properties) {
        this.properties = properties;
    }
    
    /**
     * 模板处理器Bean
     */
    @Bean
    @ConditionalOnMissingBean
    public DPKitTemplateProcessor templateProcessor(
            ObjectMapper objectMapper,
            ResourceLoader resourceLoader) {
        return new DPKitTemplateProcessor(
            objectMapper,
            resourceLoader,
            properties.getTemplateLocation());
    }
    
    /**
     * 动态实体工厂
     */
    @Bean
    @ConditionalOnMissingBean
    public DynamicEntityFactory entityFactory() {
        return new DynamicEntityFactory(
            properties.getEntityPackage(),
            properties.isBytecodeEnhanced());
    }
    
    /**
     * 核心服务
     */
    @Bean
    @ConditionalOnMissingBean
    public DPKitCoreEngine dpKitService(
            DPKitTemplateProcessor processor,
            DynamicEntityFactory entityFactory,
            ObjectProvider<OrmAdapter> ormAdapterProvider) {
        return new DPKitDPKitCoreEngineImpl(
            processor,
            entityFactory,
            ormAdapterProvider.getIfAvailable());
    }
}